Java 实例 您所在的位置:网站首页 tuple 转list Java 实例

Java 实例

2023-07-21 09:27| 来源: 网络整理| 查看: 265

文章目录 1. 方式一(最简单方式)2. 方法二(Java 8 新特性)3. 方式三(引入Jar包)

1. 方式一(最简单方式)

循环遍历

int[] ints = {1, 2, 3}; List intList = new ArrayList() ; for(int i = 0; i "123", "456"}); System.out.println("strings="+strings); List ints = Arrays.asList(new int[]{123, 456}); System.out.println("ints="+ints); //输出结果 strings=[123, 456] ints=[[I@4e515669]

这种写法有一点需要注意:基本类型>>集合,会把基本类型的数组当成一个整体结构(一个元素)存到集合中;

包装类>>集合,就不会出现基本类型转换成集合的这种情况

2. 方法二(Java 8 新特性)

使用 Java 8 的新特性,使用 Stream 流 进行转换;

想了解 Stream API 的使用可以看这篇文章 Stream API 、Lambda 表达式详解

示例

//1.创建int数组 int[] ints = {1, 2, 3}; //2.调用 Arrays 类的静态方法 Stream() 把 ints 数组对象转换成流,这里要注意需要使用 boxed() 方法把IntStream 流转化成 Stream 流,因为转化成 Stream 流之后才能调用 collect() 收集方法获得List List intList = Arrays.stream(ints).boxed().collect(Collectors.toList()); //3.最后打印输出,这里使用到了 Lambda 表达式和方法引用 intList.forEach(System.out::println); //输出结果 1 2 3

示例中调用 boxed() 方法的原因:

在这里插入图片描述

调用 Arrays 类的静态方法 stream ,如果传入一个int数组的话,调用的是一个重构方法,返回的是一个 IntStream 流对象,而如果想调用 collect() 收集方法获得List,就必须把 IntStream 流对象转换成 Stream 对象,所以 boxed() 方法就起到了这个转换作用。 在这里插入图片描述

同样 long、double数组也是这样操作:

示例

long[] longs = {1L, 2L, 3L}; double[] doubles = {1.23, 2.23, 3.23}; List longList = Arrays.stream(longs).boxed().collect(Collectors.toList()) ; List doubleList = Arrays.stream(doubles).boxed().collect(Collectors.toList()); longList.forEach(System.out::println); doubleList.forEach(System.out::println);

int、long、double 都属于基本类型,String 数组转成 List,就不需要使用 boxed() 方法

String 不属于基本类型,所以调用 Arrays 类的静态方法 stream 返回的就是 Stream 对象

示例

String[] strings = {"666" , "888" , "999"} ; List stringList = Arrays.stream(strings).collect(Collectors.toList()); stringList.forEach(System.out::println); //输出结果 666 888 999

在这里插入图片描述

3. 方式三(引入Jar包) /** * int[]转Integer[]再转List * 方法三:需要导入apache commons-lang3 jar * * org.apache.commons * commons-lang3 * 3.10 * */ int[] ints = {1, 2, 3}; //int[]转Integer[] Integer[] integers = ArrayUtils.toObject(ints); //Integer[]再转List List integerList = Arrays.asList(integers); //输出integerList integerList.forEach(System.out::println);


【本文地址】

公司简介

联系我们

今日新闻

    推荐新闻

      专题文章
        CopyRight 2018-2019 实验室设备网 版权所有